<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


if ( ! function_exists('equal_interest'))
{
		function equal_interest ($data = array()){	
		if (isset($data['style']) && $data['style']!=""){
			$style = $data['style'];
		}else{
			$style = 0;
		}
		if ($style==2){//按月还款，等额本息
			return equal_month_interest($data);
		}elseif ($style==1){//到期还本，按月付息
			return equal_endmonth_interest($data);
		}elseif ($style==3){//一次性还本还息
			return onetime_interest($data);
		}
	}
}



if ( ! function_exists('equal_month_interest_tools'))
{
	function equal_month_interest_tools ($data = array()){
		$account	 	= $data['account'];
		$year_apr 		= $data['apr'];
		$month_times 	= $data['time_limit'];
		$borrow_time 	= time();
		$reward 		= $data["reward"];
		if (isset($data['borrow_time']) && $data['borrow_time']>0){
			$borrow_time = $data['borrow_time'];
		}
        $month_apr = $year_apr/(12*100);
        if($data['is_day']==1){
        	$month_times=$data['time_limit_day']/30;
        }
        
        if($data['is_day']==1){
			$_li = pow((1+$month_apr),1);
        }else{
        	$_li = pow((1+$month_apr),$month_times); 
        }
		$repayment = round($account * ($month_apr * $_li)/($_li-1),2);
		
		$_result = array();
		if (isset($data['type']) && $data['type']=="all"){
			$_result['repayment_account'] 	= $repayment*$month_times;
			$_result['monthly_repayment'] 	= $repayment;
			$_result['month_apr'] 			= round($month_apr*100,2);
			if($reward > 0){
				$_result['rmonth_apr'] 			= round($month_apr*100,2)+round($reward/$month_times,2);
			}else{
				$_result['rmonth_apr'] 			= round($month_apr*100,2);
			}
			
		}else{
			for($i=0;$i<$month_times;$i++){
				if ($i==0){
					$interest = round($account*$month_apr,2);
				}else{
					$_lu = pow((1+$month_apr),$i);
					$interest = round(($account*$month_apr - $repayment)*$_lu + $repayment,2);
				}
                if($data['is_day']==1){
                 	if($data['type']!="all"){
                    	$_result[$i]['repayment_account'] =round($data['account']+($repayment-$data['account'])*$month_times,2);
                    }else{
						$_result[$i]['repayment_account'] = $repayment;
                    }
               		$_result[$i]['interest'] = $interest*$month_times;
                    $interest=round($interest*$month_times,2);
                }else{
                	$_result[$i]['repayment_account'] = round($repayment,2);
                	$_result[$i]['interest'] = round($interest,2);
                }
				$_result[$i]['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$i+1));
				$_result[$i]['interest'] 		= $interest;
				if($data['is_day']==1){
					$_result[$i]['capital']=$data['account'];
				}else{
					$_result[$i]['capital'] = $repayment-$interest;
				}
			}
		}
		return $_result;
	}
}
if ( ! function_exists('equal_month_interest'))
{
	function equal_month_interest ($data = array()){
		$account 		= $data['account'];
		$year_apr 		= $data['apr'];
		$month_times 	= $data['time_limit'];
		$reward 		= isset($data['reward'])?($data['reward']?$data['reward']:0):0;
		$borrow_time 	= isset($data['borrow_time'])?($data['borrow_time']?$data['borrow_time']:time()):time();
        $month_apr 		= $year_apr/(12*100);
        $_li = pow((1+$month_apr),$month_times); 

        //天标没有附加奖励
        if(isset($data['is_day']) && $data['is_day'] == 1){
        	$month_times = $data['time_limit_day']/30;
        	$_li = 1+$month_apr*$month_times;
        }
        
		$repayment = round($account * ($month_apr * $_li)/($_li-1),2);
				
		$work_times 	= $data['work_time'];//起息时间
		$instantStartingRate = 0;
		if($work_times > 0){
			//每日利率
			$work_day_apr = $year_apr/100/12/30;
			$instantStartingRate = $work_day_apr*$work_times*$account; //即时利息 
		}
					
		$_result = array();

		//
		if (isset($data['type']) && $data['type']=="all"){
			$_result['repayment_account'] 	= $repayment*$month_times;
			$_result['monthly_repayment'] 	= $repayment;
			if($data['is_day'] == 1){
				$_result['monthly_repayment'] = round($account+($repayment-$account)*$month_times,2);
			}
			$_result['month_apr'] 			= round($month_apr*100,2);
			if($reward > 0){
				$_result['rmonth_apr'] 			= round($month_apr*100,2)+round($reward/$month_times,2);
			}else{
				$_result['rmonth_apr'] 			= round($month_apr*100,2);
			}
			
		}else{
			for($i=0;$i<$month_times;$i++){
				if ($i==0){
					$interest = round($account*$month_apr,2);
					//$instantStartingRate = $instantStartingRate;
				}else{
					$_lu = pow((1+$month_apr),$i);
					$interest = round(($account*$month_apr - $repayment)*$_lu + $repayment,2);
					$instantStartingRate = 0;
				}
                if($data['is_day']==1){
                 	if(isset($data['type']) && $data['type']!="all"){
                    	$_result[$i]['repayment_account'] =round($data['account']+($repayment-$data['account'])*$month_times,2);
                    }else{
						$_result[$i]['repayment_account'] = round($repayment*$month_times,2)+$instantStartingRate;
                    }
               		$_result[$i]['interest'] = $interest*$month_times;
                    $interest=round($interest*$month_times,2);
                }else{
                	$_result[$i]['repayment_account'] = round($repayment,2)+$instantStartingRate;
                	$_result[$i]['interest'] = round($interest,2);
                }
				$_result[$i]['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$i+1));
				$_result[$i]['interest'] 		= $interest;
				$_result[$i]['worktime_interest'] = round($instantStartingRate,2);
				if($data['is_day']==1){
					$_result[$i]['capital']=$data['account'];
				}else{
					$_result[$i]['capital'] = $repayment-$interest;
				}
			}
		}
		return $_result;
	}
}

if ( ! function_exists('equal_endmonth_interest'))
{
	function equal_endmonth_interest ($data = array()){
		$is_day 		= $data['is_day'];//是否天标
		if($is_day == 1){
			return equal_end_day_interest($data);
		}
		$month_times 	= $data['time_limit'];//借款的月数
		$account 		= $data['account'];//借款的总金额
		$year_apr 		= $data['apr'];//借款的年利率
		$borrow_time 	= isset($data['borrow_time'])?($data['borrow_time']?$data['borrow_time']:time()):time();//借款的时间
		$work_times 	= $data['work_time'];//计息方式
		$instantStartingRate = 0;
		if($work_times > 0){
			//每日利率
			$day_apr = $year_apr/100/12/30;
			$instantStartingRate = round($day_apr*$work_times*$account,2); //即时利息 
		}
		
		//月利率
		$month_apr = $year_apr/(12*100);
		$_yes_account = 0 ;
		$repayment_account = 0;//总还款额
		$interest = round($account*$month_apr,2);//利息等于应还金额乘月利率
		$_result = array();
		for($i=0;$i<$month_times;$i++){
			$capital = 0;
			if ($i+1 == $month_times){
				$capital = $account;
			}
			
			if($i+1 == 1){
				$_result[$i]['repayment_account'] = $interest+$capital+$instantStartingRate;
				//$instantStartingRate = $instantStartingRate;
			}else{
				$_result[$i]['repayment_account'] = $interest+$capital;
				$instantStartingRate = 0;
			}
			
			$_result[$i]['repayment_time'] = get_times(array("time"=>$borrow_time,"num"=>$i+1));
			$_result[$i]['interest'] = $interest;
			$_result[$i]['worktime_interest'] = $instantStartingRate;
			$_result[$i]['capital'] = $capital;
		}
		if (isset($data['type']) && $data['type']=="all"){
			$_resul['repayment_account'] = $account + $interest*$month_times;
			$_resul['monthly_repayment'] = $interest;
			$_resul['month_apr'] = round($month_apr*100,2);
			$_resul['repayment_end_time'] = get_times(array("time"=>$borrow_time,"num"=>$month_times));
			return $_resul;
		}else{
			return $_result;
		}
	}
}

if ( ! function_exists('equal_end_day_interest'))
{
	function equal_end_day_interest ($data = array()){
		$is_day 		= $data['is_day'];//是否天标
		$month_times 	= $data['time_limit'];//借款的月数
		$account 		= $data['account'];//借款的总金额
		$year_apr 		= $data['apr'];//借款的年利率
		$borrow_time 	= isset($data['borrow_time'])?($data['borrow_time']?$data['borrow_time']:time()):time();//借款的时间
		$tmonth = 0;
		$tday = 0;
		if($is_day == 1){
			$tmonth = ceil($month_times/30);
			$tday = $month_times-($tmonth-1)*30;
		}
		
		//月利率
		$month_apr 	= $year_apr/12;
		$day_apr 	= $month_apr/30;
		$interest = round($account*$month_apr/100,2);//利息等于应还金额乘月利率
		$_result = array();
		
		$work_times 	= $data['work_time'];//起息时间
		$instantStartingRate = 0;
		if($work_times > 0){
			//每日利率
			$work_day_apr = $year_apr/100/12/30;
			$instantStartingRate = $work_day_apr*$work_times*$account; //即时利息 
		}
		
		for($i=0;$i<$tmonth;$i++){
			$capital = 0;
			if ($i+1 == $tmonth){
				$capital = $account;
				$interest = $account*$tday*$day_apr/100;
				$_result[$i]['repayment_time'] = get_times(array("time"=>$borrow_time,"num"=>$month_times,'type'=>'day'));
				
			}else{
				$_result[$i]['repayment_time'] = get_times(array("time"=>$borrow_time,"num"=>$i+1));
			}
			
			if($i+1 ==  1){
				$_result[$i]['repayment_account'] 	= round($interest+$capital+$instantStartingRate,2);
			}else{
				$_result[$i]['repayment_account'] 	= round($interest+$capital,2);
			}
			
			$_result[$i]['interest'] 			= round($interest,2);
			$_result[$i]['worktime_interest'] = round($instantStartingRate,2);
			$_result[$i]['capital'] 			= round($capital,2);
		}
		if (isset($data['type']) && $data['type']=="all"){
			$_resul['repayment_account'] = round($account + $day_apr*$month_times*$account/100,2);
			$_resul['monthly_repayment'] = round($day_apr*$month_times*$account/100,2);
			$_resul['month_apr'] = round($month_apr*100,2);
			$_resul['repayment_end_time'] = get_times(array("time"=>$borrow_time,"num"=>$month_times,'type'=>'day'));
			return $_resul;
		}else{
			return $_result;
		}
	}
}
if( ! function_exists('onetime_interest')){
	function onetime_interest($data = array()){
		$account 		= $data['account'];
		$year_apr 		= $data['apr'];
		
		$month_times 	= $data['time_limit'];
		
	 	if($data['is_day']==1){
        	$month_times 	= $data['time_limit_day'];
        }
		$reward 		= isset($data['reward'])?($data['reward']?$data['reward']:0):0;
		$borrow_time 	= isset($data['borrow_time'])?($data['borrow_time']?$data['borrow_time']:time()):time();
		$is_day			= $data['is_day'];
        $month_apr 		= $year_apr/12;
        $day_apr		= 0.00;
        if(isset($is_day) && $is_day == 1){
        	//$day_apr = round(floor($month_apr*1000)/1000,3);
        	$day_apr = $month_apr/30;
        }
		$work_times 	= $data['work_time'];//起息时间
		$instantStartingRate = 0;
		if($work_times > 0){
			// 每日利率
			$work_day_apr = $year_apr/100/12/30;
			$instantStartingRate = $work_day_apr*$work_times*$account; // 即时利息 
		}
		
		$_result = array();
		if (isset($data['type']) && $data['type']=="all"){
			if($is_day == 1){
				$_result['repayment_account'] 	= round($account+$account*$month_times*$day_apr/100,2);
				$_result['monthly_repayment'] 	= round($account+$account*$month_times*$day_apr/100,2);
				$_result['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$month_times,"type"=>'day'));
			}else{
				$_result['repayment_account'] 	= round($account+$account*$month_times*$month_apr/100,2);
				$_result['monthly_repayment'] 	= round($account+$account*$month_times*$month_apr/100,2);
				$_result['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$month_times,"type"=>'month'));
			}
			$_result['month_apr'] 			= round($month_apr*100,2);
			$_result['rmonth_apr'] 			= round($account*$month_apr/100,2);		
			
		}else{
            if($is_day==1){
            	$_result[0]['repayment_account'] =round($account+$account*$month_times*$day_apr/100,2)+$instantStartingRate;
               	$_result[0]['interest'] = round($account*$month_times*$day_apr/100, 2);
               	$_result[0]['worktime_interest'] = round($instantStartingRate,2);
               	$_result[0]['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$month_times,"type"=>'day'));
            }else{
            	$_result[0]['repayment_account'] = round($account+$account*$month_times*$month_apr/100,2)+$instantStartingRate;
                $_result[0]['interest'] = round($account*$month_times*$month_apr/100,2);
                $_result[0]['worktime_interest'] = round($instantStartingRate,2);
                $_result[0]['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$month_times,"type"=>'month'));
            }
			$_result[0]['capital']=$account;
		}
		return $_result;
	}
}

if ( ! function_exists('get_times'))
{
	//获得时间天数
	function get_times($data=array()){
		if (isset($data['time']) && $data['time']!=""){
			$time = $data['time'];//时间
		}elseif (isset($data['date']) && $data['date']!=""){
			$time = strtotime($data['date']);//日期
		}else{
			$time = time();//现在时间
		}
		if (isset($data['type']) && $data['type']!=""){ 
			$type = $data['type'];//时间转换类型，有day week month year
		}else{
			$type = "month";
		}
		if (isset($data['num']) && $data['num']!=""){ 
			$num = $data['num'];
		}else{
			$num = 1;
		}
		
		//TODO ******by lib 20150103  待检测后开启自然月还款
		// 更正时间获取异常，以$data['time']进入则进行更改

		
		// 兼容原程序非$data['time']处理流程
		if ($type=="month"){
			$month = date("m",$time);
			$year = date("Y",$time);
			$_result = strtotime("$num month",$time);
			$_month = (int)date("m",$_result);
			if ($month+$num>24){
				$_num = $month+$num-24;
				$year = $year+2;
			}elseif ($month+$num>12){
				$_num = $month+$num-12;
				$year = $year+1;
			}else{
				$_num = $month+$num;
			}
			if ($_num!=$_month){
				$_result = strtotime("-1 day",strtotime("{$year}-{$_month}-01"));
			}
		}else{
			$_result = strtotime("$num $type",$time);
		}
		if (isset($data['format']) && $data['format']!=""){ 
			return date($data['format'],$_result);
		}else{
			return $_result;
		}
	}
}



if ( ! function_exists('get_mktime')){
	function get_mktime($mktime){
		if ($mktime=="") return "";
		$dtime = $mktime;
		$ds = explode(" ",$dtime);
		$ymd = explode("-",$ds[0]);
		if (isset($ds[1]) && $ds[1]!=""){
			$hms = explode(":",$ds[1]);
			$mt = mktime(empty($hms[0])?0:$hms[0],!isset($hms[1])?0:$hms[1],!isset($hms[2])?0:$hms[2],!isset($ymd[1])?0:$ymd[1],!isset($ymd[2])?0:$ymd[2],!isset($ymd[0])?0:$ymd[0]);
		}else{
			$mt = mktime(0,0,0,!isset($ymd[1])?0:$ymd[1],!isset($ymd[2])?0:$ymd[2],!isset($ymd[0])?0:$ymd[0]);
		}
		
		return $mt;
	}
}
if ( ! function_exists('late_interest')){
	//逾期利息计算
	//account 金额 repayment_time 还款时间
	function late_interest($repayment_time, $account){
		$now_time = get_mktime(date("Y-m-d",time()));
		$repayment_time = get_mktime(date("Y-m-d",$repayment_time));
		$late_days = ($now_time - $repayment_time)/(60*60*24);
		$_late_days = explode(".",$late_days);
		$late_days = ($_late_days[0]<0)?0:$_late_days[0];
		if($late_days <= 30){
			$late_interest = round($account*CON_LATE_RATE*$late_days,2);
		}elseif($late_days > 30){
			$late_interest = round($account*CON_LATE_RATE1*$late_days,2);
		}
		if ($late_days==0) {
			$late_interest=0;
		}
		return array("late_days"=>$late_days,"late_interest"=>$late_interest );
	}
}
if ( ! function_exists('equal_month_tools')){
	function equal_month_tools ($data = array()){
		if (isset($data['account']) && $data['account']>0){
			$account = $data['account'];
		}else{
			return "";
		}
		
		if (isset($data['apr']) && $data['apr']>0){
			$year_apr = $data['apr'];
		}else{
			return "";
		}
		
		if (isset($data['time_limit']) && $data['time_limit']>0){
			$month_times = $data['time_limit'];
		}
		if (isset($data['borrow_time']) && $data['borrow_time']>0){
			$borrow_time = $data['borrow_time'];
		}else{
			$borrow_time = time();
		}
        $month_apr = $year_apr/(12*100);
        if($data['is_day']==1){
        	$month_times=$month_times*$data['time_limit_day']/30;
        }
        if($data['is_day']==1){
			$_li = pow((1+$month_apr),1);
        }else{
        	$_li = pow((1+$month_apr),$month_times); 
        }
        
		$repayment = round($account * ($month_apr * $_li)/($_li-1),2);
		
		$_result = array();
		if (isset($data['type']) && $data['type']=="all"){
			$_result['repayment_account'] 	= $repayment*$month_times;
			$_result['monthly_repayment'] 	= $repayment;
			$_result['month_apr'] 			= round($month_apr*100,2);
			$_result['rmonth_apr'] 			= round($month_apr*100,2)+round($data["reward"]/$month_times,2);
		}else{
			for($i=0;$i<$month_times;$i++){
				if ($i==0){
					$interest = round($account*$month_apr,2);
				}else{
					$_lu = pow((1+$month_apr),$i);
					$interest = round(($account*$month_apr - $repayment)*$_lu + $repayment,2);
				}
                if($data['is_day']==1){
                 	if($data['type']!="all"){
                    	$_result[$i]['repayment_account'] =round($data['account']+($repayment-$data['account'])*$month_times,2);
                    }else{
						$_result[$i]['repayment_account'] = $repayment;
                    }
               		$_result[$i]['interest'] = $interest*$month_times;
                    $interest=round($interest*$month_times,2);
                }else{
                	$_result[$i]['repayment_account'] = round($repayment,2);
                	$_result[$i]['interest'] = round($interest,2);
                }
				$_result[$i]['repayment_time'] 	= get_times(array("time"=>$borrow_time,"num"=>$i+1));
				$_result[$i]['interest'] 		= $interest;
				if($data['is_day']==1){
					$_result[$i]['capital']=$data['account'];
				}else{
					$_result[$i]['capital'] = $repayment-$interest;
				}
			}
		}
		return $_result;
	}
}


if ( ! function_exists('POSTDATA')){
	function POSTDATA($url, $data)
	{
	
		$url = parse_url($url);
		if (!$url)
		{
			RecordLog("couldn't parse url");
			return "couldn't parse url";
		}
		
		if (!isset($url['port'])) { $url['port'] = ""; }
	
		if (!isset($url['query'])) { $url['query'] = ""; }
	
	
		$encoded = "";
	
		while (list($k,$v) = each($data))
		{
			$encoded .= ($encoded ? "&" : "");
			$encoded .= rawurlencode($k)."=".rawurlencode($v);
		}
		$urlHead = null;
		$urlPort = $url['port'];
		if($url['scheme'] == "https")
		{
			$urlHead = "ssl://".$url['host'];
			if($url['port'] == null || $url['port'] == 0)
			{
				$urlPort = 443;
			}
		}
		else
		{
			$urlHead = $url['host'];
			if($url['port'] == null || $url['port'] == 0)
			{
				$urlPort = 80;
			}
		}
		
		RecordLog("YGM",$urlHead);
		
		$fp = fsockopen($urlHead, $urlPort);
		
		
		if (!$fp) return "Failed to open socket to $url[host]";
	
		$tmp="";
		$tmp.=sprintf("POST %s%s%s HTTP/1.0\r\n", $url['path'], $url['query'] ? "?" : "", $url['query']);
		$tmp.="Host: $url[host]\r\n";
		$tmp.="Content-type: application/x-www-form-urlencoded\r\n";
		$tmp.="Content-Length: " . strlen($encoded) . "\r\n";
		$tmp.="Connection: close\r\n\r\n";
		$tmp.="$encoded\r\n";
		
		fputs($fp,$tmp);
	
		$line = fgets($fp,1024);
		
		if (!preg_match("#^HTTP/1\.. 200#i", $line))
		{
			$logstr = "MSG".$line;
			RecordLog("YGM",$logstr);
			return array("FLAG"=>0,"MSG"=>$line);
		}
	
		$results = ""; $inheader = 1;
		while(!feof($fp))
		{
			$line = fgets($fp,1024);
			if ($inheader && ($line == "\n" || $line == "\r\n"))
			{
				$inheader = 0;
			}
			elseif (!$inheader)
			{
				$results .= $line;
			}
		}
		fclose($fp);
		return array("FLAG"=>1,"MSG"=>$results);
	} 
}

if ( ! function_exists('parseRecv')){
	function parseRecv($source)
	{
		$ret = array();
		$temp = explode("&",$source);
		
		foreach ($temp as $value)
		{
			$index=strpos($value,"=");
			$_key=substr($value,0,$index);
			$_value=substr($value,$index+1);
			$ret[$_key] = $_value;
		}
	
		return $ret;
	}
}
if ( ! function_exists('MD5sign')){
	//MD5方式签名
	function MD5sign($okey,$odata)
	{
		 $signdata=hmac("",$odata);			     
		 return hmac($okey,$signdata);
	}
}


if ( ! function_exists('hmac')){
	function hmac ($key, $data)
	{
	  $key = iconv('gb2312', 'utf-8', $key);
	  $data = iconv('gb2312', 'utf-8', $data);
	  $b = 64;
	  if (strlen($key) > $b) {
	  $key = pack("H*",md5($key));
	  }
	  $key = str_pad($key, $b, chr(0x00));
	  $ipad = str_pad('', $b, chr(0x36));
	  $opad = str_pad('', $b, chr(0x5c));
	  $k_ipad = $key ^ $ipad ;
	  $k_opad = $key ^ $opad;
	 return md5($k_opad . pack("H*",md5($k_ipad . $data)));
	} 
} 





/*
	功能：把UTF-8 编号数据转换成 GB2312 忽略转换错误
*/
if ( ! function_exists('decodeUtf8')){
	function decodeUtf8($source)
	{
		$temp = urldecode($source);
		$ret = iconv("UTF-8","GB2312//IGNORE",$temp);
		return $ret;
	}
}

if ( ! function_exists('RecordLog')){
	function RecordLog($uname, $text) {
	   $date_time = date("Y年m月d H:i:s");
	   $LOG_FILE = "./log/".date("Ymd").$uname.".txt";
	   $text = "$date_time  ".$text;
	
	   if (!file_exists($LOG_FILE)) {
	    touch($LOG_FILE);
	    //chmod($LOG_FILE,"744");
	   }
	
	   $fd = @fopen($LOG_FILE, "a");
	   @fwrite($fd, $text."\r\n");
	   @fclose($fd);
	}
}

if ( ! function_exists('RecordMyLog')){
	function RecordMyLog($text) {
		RecordLog("YGM",$text);
	}
}

if ( ! function_exists('parseUrl')){
	//返回URL处理
	function parseUrl($payUrl)
	{
		$temp =explode("<hi:$$>",$payUrl);			
		$url_lst=explode("<hi:=>",$temp[0]);
		$url=$url_lst[1];
		$method_lst=explode("<hi:=>",$temp[1]);
		$method=$method_lst[1];
		$sessionid_lst=explode("<hi:=>",$temp[2]);
		$sessionid=$sessionid_lst[1];
		$url=$url."?SESSIONID=".$sessionid;
		$rpayUrl = array();		
		$rpayUrl["url"]=$url;
		$rpayUrl["method"]=$method;
		return $rpayUrl;
	}
}